package com.studyroom.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.studyroom.entity.EmailVerificationCode;
import com.studyroom.entity.User;
import com.studyroom.exception.ServiceException;
import com.studyroom.mapper.EmailVerificationCodeMapper;
import com.studyroom.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Random;

@Service
@Slf4j
public class VerificationCodeService {

    @Autowired
    private EmailVerificationCodeMapper codeMapper;
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private EmailService emailService;
    
    // 生成验证码
    private String generateCode() {
        // 6位数字验证码
        Random random = new Random();
        int code = 100000 + random.nextInt(900000);
        return String.valueOf(code);
    }
    
    // 发送验证码
    @Transactional
    public void sendVerificationCode(String username, String email) {
        // 检查用户是否存在且邮箱匹配
        User user = userMapper.selectOne(
            new LambdaQueryWrapper<User>()
                .eq(User::getUsername, username)
        );
        
        if (user == null) {
            log.warn("用户不存在: {}", username);
            throw new ServiceException("用户名不存在");
        }
        
        if (!email.equals(user.getEmail())) {
            log.warn("邮箱不匹配. 用户: {}, 提供的邮箱: {}, 实际邮箱: {}", username, email, user.getEmail());
            throw new ServiceException("用户名与邮箱不匹配");
        }
        
        // 生成验证码
        String code = generateCode();
        
        // 设置过期时间（10分钟后）
        LocalDateTime expiresAt = LocalDateTime.now().plusMinutes(10);
        
        // 保存验证码
        EmailVerificationCode verificationCode = new EmailVerificationCode();
        verificationCode.setUsername(username);
        verificationCode.setEmail(email);
        verificationCode.setCode(code);
        verificationCode.setExpiresAt(expiresAt);
        verificationCode.setIsUsed(0);
        
        codeMapper.insert(verificationCode);
        
        // 发送邮件
        emailService.sendVerificationCode(email, code);
    }
    
    // 验证验证码
    @Transactional
    public boolean verifyCode(String username, String email, String code) {
        // 查询最近的未使用的验证码
        EmailVerificationCode verificationCode = codeMapper.selectOne(
            new LambdaQueryWrapper<EmailVerificationCode>()
                .eq(EmailVerificationCode::getUsername, username)
                .eq(EmailVerificationCode::getEmail, email)
                .eq(EmailVerificationCode::getCode, code)
                .eq(EmailVerificationCode::getIsUsed, 0)
                .gt(EmailVerificationCode::getExpiresAt, LocalDateTime.now())
                .orderByDesc(EmailVerificationCode::getCreatedAt)
                .last("LIMIT 1")
        );
        
        if (verificationCode != null) {
            // 标记验证码已使用
            verificationCode.setIsUsed(1);
            codeMapper.updateById(verificationCode);
            return true;
        }
        
        return false;
    }
} 